<?php

class LoginController extends ControllerBase
{
	public $defaultAction = 'user';

	/**
	 * Displays the login page
	 */
	public function actionAdmin()
	{
		if (!Util::isSuperMod()) {
			$model=new UserLogin;
			// collect user input data
			if(isset($_POST['UserLogin']))
			{
				$model->attributes=$_POST['UserLogin'];
				// validate user input and redirect to previous page if valid
				if($model->validate()) {
					$this->lastViset('admin');
					$checkReturnAdmin = self::checkLinkModule();
					if ($checkReturnAdmin)
						$this->redirect(Yii::app()->user->returnUrl);
					else
						$this->redirect(Yii::app()->controller->module->returnUrl);
				}
			}
			// display the login form
			$this->render('/admin/login',array('model'=>$model));
		} else
			$this->redirect(Yii::app()->controller->module->returnUrl);
	}
	public function actionUser()
	{
		Util::app()->theme 	= SITE_THEME;
		$this->layout 		= '//layouts/none';

		if (Yii::app()->user->isGuest) {
			$model=new UserLogin;
			// collect user input data
			if(isset($_POST['UserLogin']))
			{
				$model->attributes=$_POST['UserLogin'];
				$model->username = ($model->username == '--Tài khoản--') ? '' : $model->username;
				$model->password = ($model->password == '--Mật khẩu--') ? '' : $model->password;

				// validate user input and redirect to previous page if valid
				if($model->validate()) {
					$this->lastViset('user');
					self::navigateLogin();
				}
			}
			// display the login form
			$this->render('/user/login',array('model'=>$model));
		}
		else {
			self::navigateLogin();
		}
	}

	/*
	 * navigateLogin
	 */
	private function navigateLogin () {
		if (User::model()->checkActiveFirstLogin()) {
			$this->redirect(array('/authenticate/password'));
		}
		else if (Util::isRegister()){
			//Yii::app()->user->id
			$member	= Member::model()->findByPk(Yii::app()->user->id);
			if ($member->avatar == "") {
				$this->redirect(array('/authenticate/avatar'));
			}
			else {
				$this->redirect(array('/authenticate/profile'));
			}
		}
		else {
			if (!self::checkLinkModule())
				$this->redirect(Yii::app()->user->returnUrl);
			else
				$this->redirect('site');
		}
	}

	/*
	 * checkLinkModule()
	 */
	private function checkLinkModule(){
		$check 		= false;
		$listModule = Util::getListModule();
		$returnUrl	= Yii::app()->user->returnUrl;
		$linkCheck	= array_values(array_filter(explode('/', $returnUrl)));

		if ($returnUrl != '/index.php' && ((isset($linkCheck[0]) && in_array($linkCheck[0], $listModule)) || (isset($linkCheck[1]) && in_array($linkCheck[1], $listModule))))
			$check = true;

		return $check;
	}

	/*
	 * lastViset()
	 */
	private function lastViset($type) {
		$lastVisit = User::model()->notsafe()->findByPk(Yii::app()->user->id);
		$lastVisit->lastvisit = time();
		$lastVisit->save();
	}

}